import { dispatch } from "../StoreUtil"

/**
 * store 操作基类
 * 所有的reducer继承此类，传入构造函数的参数
 * 如有别的操作，Reducer.actions.setValue({next: 99, otherFn: 'aa'})
 * otherFn 是需要对数据特殊处理的方法，需要在reducer里实现对应的方法名称
 * @class InterfaceReducer
 */
class InterfaceReducer{
    
    constructor(initObj) {
        const {key, initState, PATH = '/REDUCER_PATH'} = initObj;
        this.key = key;
        this.initState = initState;
        const REDUCER_PATH = `${key}/${PATH}]`;
        this.REDUCER_PATH = REDUCER_PATH
        this.actionHandlers = {
            [REDUCER_PATH]: (state, action) => ({
                ...state,
                ...this.getFinState(action.value)
            })
        }
    }

    initState = {}

    key;

    REDUCER_PATH;

    setValue = (value) => (
        dispatch({
            type: this.REDUCER_PATH,
            value: value
        })
    )

    actions = {
        setValue: this.setValue
    }

    actionHandlers = {}

    //处理最终的修改数据
    getFinState = (value) => {
        let finValue = {};
        let _that = this;
        if(value.otherFn) {
            finValue = _that[value.otherFn](value)
        }else{
            for(let key in value) {
                if(this.initState[key] !== undefined) {
                    finValue[key] = value[key];
                }
            }
        }
        return finValue
    }
}

export default InterfaceReducer